package com.matrix.index.ui.setting

import android.Manifest.permission.READ_EXTERNAL_STORAGE
import android.Manifest.permission.READ_MEDIA_IMAGES
import android.Manifest.permission.READ_MEDIA_VIDEO
import android.Manifest.permission.READ_MEDIA_VISUAL_USER_SELECTED
import android.Manifest.permission.WRITE_EXTERNAL_STORAGE
import android.content.ActivityNotFoundException
import android.content.Intent
import android.content.pm.PackageManager.PERMISSION_GRANTED
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.Settings
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import androidx.core.view.isGone
import com.alibaba.android.arouter.facade.annotation.Route
import com.matrix.basecore.base.BaseActivity
import com.matrix.basecore.constant.Constant
import com.matrix.index.databinding.ActivityCardShareBinding
import java.io.File


@Route(path = Constant.ARouterPath.CardShareActivityPath)
class CardShareActivity : BaseActivity<ActivityCardShareBinding>() {

    private var path = ""

    private val permissionLauncher =
        registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { permissions ->
            checkPermission()
        }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
    }

    override fun getViewBinding(): ActivityCardShareBinding {
        enableEdgeToEdge()
        return ActivityCardShareBinding.inflate(layoutInflater)
    }

    override fun initView() {
        path =
            Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).path + File.separator + "matrix"
        requestPermissions()
    }

    private fun requestPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
            permissionLauncher.launch(
                arrayOf(
                    READ_MEDIA_IMAGES,
                    READ_MEDIA_VIDEO,
                    WRITE_EXTERNAL_STORAGE,
                    READ_EXTERNAL_STORAGE
                )
            )
        } else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.TIRAMISU) {
            permissionLauncher.launch(
                arrayOf(
                    READ_MEDIA_IMAGES,
                    READ_MEDIA_VIDEO,
                    WRITE_EXTERNAL_STORAGE,
                    READ_EXTERNAL_STORAGE
                )
            )
        } else {
            permissionLauncher.launch(arrayOf(READ_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE))
        }
    }

    private fun checkPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU
            && (ContextCompat.checkSelfPermission(this, READ_MEDIA_IMAGES) == PERMISSION_GRANTED
                    || ContextCompat.checkSelfPermission(
                this,
                READ_MEDIA_VIDEO
            ) == PERMISSION_GRANTED)
        ) {
            mViewBinding.text.isGone = true
            //获得权限
            openAssignFolder(path)
            // Full access on Android 13 (API level 33) or higher
        } else if (
            Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE &&
            ContextCompat.checkSelfPermission(
                this,
                READ_MEDIA_VISUAL_USER_SELECTED
            ) == PERMISSION_GRANTED
        ) {
            // Partial access on Android 14 (API level 34) or higher
            mViewBinding.text.text = "你已授权访问部分文件权限，点击添加更多"
            openAssignFolder(path)
        } else if (ContextCompat.checkSelfPermission(
                this,
                READ_EXTERNAL_STORAGE
            ) == PERMISSION_GRANTED
        ) {
            openAssignFolder(path)
            // Full access up to Android 12 (API level 32)
        } else {
            // Access denied
            mViewBinding.text.text = "你还未授权访问文件权限，点击申请"
        }
    }

    override fun initListener() {
        mViewBinding.text.setOnClickListener {
            var intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            var uri = Uri.fromParts("package", packageName, null);
            intent.setData(uri)
            startActivity(intent)
        }
    }

    private fun openAssignFolder(path: String) {
        var file = File(path)
        if (null == file || !file.exists()) {
            return
        }
        val fileUri = FileProvider.getUriForFile(
            this,
            application.packageName+".fileProvider",
            file
        )
        var intent = Intent(Intent.ACTION_GET_CONTENT);
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(fileUri, "file/*");
        try {
            startActivity(intent)
        } catch (e: Exception) {
            e.printStackTrace();
        }
    }
}